﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;
using System.Threading;

namespace _008_RabbitMqReceived
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("欢迎进入消息显示栏!");
            ConnectionFactory factory = new ConnectionFactory();
            factory.HostName = "192.168.16.102";
            factory.UserName = "admin";
            factory.Password = "admin";

            using (var con = factory.CreateConnection())
            {
                using (var route1 = con.CreateModel())
                {
                    //生产者-消费者模式
                    //Product_Consume_Recived(route1);

                    //广播模式
                    Fanout_Recived(route1);


                    while (Char.ToLower(Console.ReadKey().KeyChar) != 'q')
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
        }

        private static void Fanout_Recived(IModel route1)
        {
            string exchangeName = "myExchange";
            string tempQueue = route1.QueueDeclare().QueueName;
            route1.QueueBind(tempQueue, exchangeName, "");

            var consumer = new EventingBasicConsumer(route1);
            route1.BasicConsume(tempQueue, false, consumer);
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body.Span;
                var msg = Encoding.UTF8.GetString(body);
                Console.WriteLine($"{DateTime.Now}:{msg}");
                route1.BasicAck(ea.DeliveryTag, false);
            };
        }

        private static void Product_Consume_Recived(IModel route1)
        {
            string routeName = "myRoute1";
            //route1.QueueDeclare(routeName, false, false, false, null);

            var consumer = new EventingBasicConsumer(route1);
            route1.BasicConsume(routeName, false, consumer);

            consumer.Received += (model, ea) =>
            {
                var body = ea.Body.Span;
                var msg = Encoding.UTF8.GetString(body);
                Console.WriteLine($"{DateTime.Now}:{msg}");
                route1.BasicAck(ea.DeliveryTag, false);
            };
        }
    }
}
